class_name BattleManager extends Node

# 战斗状态枚举
enum BattleState {
    INIT,           # 初始化
    START,          # 战斗开始
    PLAYER_TURN,    # 玩家回合
    ENEMY_TURN,     # 敌方回合
    VICTORY,        # 胜利
    DEFEAT,         # 失败
    END             # 战斗结束
}

# 当前战斗状态
var current_state = BattleState.INIT

# 战斗参与者
var player_monsters = []  # 玩家的幻兽队伍
var enemy_monsters = []   # 敌方的幻兽队伍

# 当前行动的幻兽
var current_monster = null

# 回合计数
var turn_count = 0

# 战斗日志
var battle_log = []

# 战斗结果回调
signal battle_ended(result)
signal turn_changed(turn_type, monster)
signal monster_action(monster, target, action_result)
signal monster_defeated(monster)

# 初始化战斗
func initialize_battle(player_team, enemy_team):
    player_monsters = player_team
    enemy_monsters = enemy_team
    current_state = BattleState.INIT
    turn_count = 0
    battle_log = []
    
    print("战斗初始化完成")
    print("玩家队伍: %d 只幻兽" % player_monsters.size())
    print("敌方队伍: %d 只幻兽" % enemy_monsters.size())
    
    for monster in player_monsters:
        print("玩家幻兽: %s (Lv.%d)" % [monster.monster_name, monster.level])
    
    for monster in enemy_monsters:
        print("敌方幻兽: %s (Lv.%d)" % [monster.monster_name, monster.level])
    
    return true

# 开始战斗
func start_battle():
    if current_state != BattleState.INIT:
        print("错误: 战斗尚未初始化")
        return false
    
    current_state = BattleState.START
    _add_to_log("战斗开始!")
    
    # 决定首先行动的一方
    _determine_first_turn()
    
    return true

# 决定首先行动的一方
func _determine_first_turn():
    # 简单实现: 比较双方第一只幻兽的速度
    if player_monsters.size() > 0 and enemy_monsters.size() > 0:
        var player_speed = player_monsters[0].speed
        var enemy_speed = enemy_monsters[0].speed
        
        if player_speed >= enemy_speed:
            _start_player_turn()
        else:
            _start_enemy_turn()
    else:
        print("错误: 战斗队伍为空")
        end_battle(BattleState.END)

# 开始玩家回合
func _start_player_turn():
    current_state = BattleState.PLAYER_TURN
    current_monster = player_monsters[0]  # 简化: 总是使用第一只幻兽
    turn_count += 1
    
    _add_to_log("回合 %d: 玩家的回合" % turn_count)
    emit_signal("turn_changed", "player", current_monster)
    
    # 注意: 在实际游戏中，这里会等待玩家输入

# 开始敌方回合
func _start_enemy_turn():
    current_state = BattleState.ENEMY_TURN
    current_monster = enemy_monsters[0]  # 简化: 总是使用第一只幻兽
    
    _add_to_log("回合 %d: 敌方的回合" % turn_count)
    emit_signal("turn_changed", "enemy", current_monster)
    
    # AI决策
    _enemy_ai_action()

# 敌方AI决策
func _enemy_ai_action():
    if enemy_monsters.size() == 0 or player_monsters.size() == 0:
        _check_battle_end()
        return
    
    var enemy = enemy_monsters[0]
    var target = player_monsters[0]
    
    # 简单AI: 随机选择技能
    var skill_index = randi() % enemy.skills.size()
    
    _add_to_log("%s 对 %s 使用了技能!" % [enemy.monster_name, target.monster_name])
    
    var action_result = enemy.use_skill(skill_index, target)
    if action_result:
        var is_defeated = target.take_damage(action_result.damage)
        
        _add_to_log("%s 受到了 %d 点伤害!" % [target.monster_name, action_result.damage])
        emit_signal("monster_action", enemy, target, action_result)
        
        if is_defeated:
            _add_to_log("%s 被击败了!" % target.monster_name)
            emit_signal("monster_defeated", target)
            player_monsters.erase(target)
    
    # 检查战斗是否结束
    if _check_battle_end():
        return
    
    # 切换到玩家回合
    _start_player_turn()

# 玩家行动
func player_action(action_type, skill_index = -1, item_index = -1):
    if current_state != BattleState.PLAYER_TURN:
        print("错误: 不是玩家的回合")
        return false
    
    if player_monsters.size() == 0 or enemy_monsters.size() == 0:
        _check_battle_end()
        return false
    
    var player = player_monsters[0]
    var target = enemy_monsters[0]
    
    match action_type:
        "attack":
            # 基础攻击
            _add_to_log("%s 对 %s 发动了攻击!" % [player.monster_name, target.monster_name])
            
            var damage = max(1, player.attack - target.defense)
            var is_defeated = target.take_damage(damage)
            
            _add_to_log("%s 受到了 %d 点伤害!" % [target.monster_name, damage])
            emit_signal("monster_action", player, target, {"damage": damage, "effects": []})
            
            if is_defeated:
                _add_to_log("%s 被击败了!" % target.monster_name)
                emit_signal("monster_defeated", target)
                enemy_monsters.erase(target)
        
        "skill":
            # 使用技能
            if skill_index < 0 or skill_index >= player.skills.size():
                print("错误: 无效的技能索引")
                return false
            
            _add_to_log("%s 对 %s 使用了技能!" % [player.monster_name, target.monster_name])
            
            var action_result = player.use_skill(skill_index, target)
            if action_result:
                var is_defeated = target.take_damage(action_result.damage)
                
                _add_to_log("%s 受到了 %d 点伤害!" % [target.monster_name, action_result.damage])
                emit_signal("monster_action", player, target, action_result)
                
                if is_defeated:
                    _add_to_log("%s 被击败了!" % target.monster_name)
                    emit_signal("monster_defeated", target)
                    enemy_monsters.erase(target)
        
        "item":
            # 使用道具
            _add_to_log("%s 使用了道具!" % player.monster_name)
            # 这里将来会实现道具使用逻辑
        
        "run":
            # 逃跑
            _add_to_log("玩家尝试逃跑!")
            
            # 简单实现: 50%的逃跑成功率
            if randf() < 0.5:
                _add_to_log("逃跑成功!")
                end_battle(BattleState.END)
                return true
            else:
                _add_to_log("逃跑失败!")
    
    # 检查战斗是否结束
    if _check_battle_end():
        return true
    
    # 切换到敌方回合
    _start_enemy_turn()
    return true

# 检查战斗是否结束
func _check_battle_end():
    if player_monsters.size() == 0:
        # 玩家失败
        _add_to_log("战斗失败!")
        end_battle(BattleState.DEFEAT)
        return true
    
    if enemy_monsters.size() == 0:
        # 玩家胜利
        _add_to_log("战斗胜利!")
        end_battle(BattleState.VICTORY)
        return true
    
    return false

# 结束战斗
func end_battle(result):
    current_state = result
    
    match result:
        BattleState.VICTORY:
            _add_to_log("战斗胜利! 获得经验值和奖励!")
            # 这里将来会实现经验值和奖励分配
            for monster in player_monsters:
                var exp_gain = 50  # 简化: 固定经验值
                _add_to_log("%s 获得了 %d 点经验值!" % [monster.monster_name, exp_gain])
                monster.add_experience(exp_gain)
        
        BattleState.DEFEAT:
            _add_to_log("战斗失败! 返回安全区域...")
        
        BattleState.END:
            _add_to_log("战斗结束.")
    
    emit_signal("battle_ended", result)
    return true

# 添加战斗日志
func _add_to_log(message):
    battle_log.append(message)
    print("战斗日志: " + message)

# 获取战斗日志
func get_battle_log():
    return battle_log

# 获取当前战斗状态
func get_battle_state():
    return current_state

# 获取战斗状态名称
func get_battle_state_name(state = null):
    if state == null:
        state = current_state
    
    match state:
        BattleState.INIT:
            return "初始化"
        BattleState.START:
            return "开始"
        BattleState.PLAYER_TURN:
            return "玩家回合"
        BattleState.ENEMY_TURN:
            return "敌方回合"
        BattleState.VICTORY:
            return "胜利"
        BattleState.DEFEAT:
            return "失败"
        BattleState.END:
            return "结束"
        _:
            return "未知"
